package ldh.im.fxbase.dao;

import ldh.im.fxbase.data.pojo.ImLabel;
import ldh.im.fxbase.data.pojo.ext.ImLabelExt;
import ldh.im.fxbase.util.DbUtil;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ImLabelDao extends BaseDao {

    private static final String COLLECT_COLUMNS = "id, serverId, currentUserId, name, status statusValue, createTime, updateTime";

    public void insert(ImLabel imLabel) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            ResultSetHandler<Long> resultSetHandler = new ScalarHandler();
            String sql = String.format("insert into im_label(serverId, currentUserId, name, status, createTime, updateTime) values(?, ?, ?, ?, ?, ?)");
            Long id = queryRunner.insert(connection, sql, resultSetHandler, imLabel.getServerId(), imLabel.getCurrentUserId(), imLabel.getName(),
                    valueEnum(imLabel.getStatus()), imLabel.getCreateTime(), imLabel.getUpdateTime());
            imLabel.setId(id);
            return imLabel;
        });
    }

    public void batchInserts(List<ImLabel> imLabels) throws SQLException {
        if (imLabels.size() < 1) return;
        Object[][] params = imLabels.stream().map(imLabel-> new Object[]{imLabel.getServerId(), imLabel.getCurrentUserId(), imLabel.getName(),
                valueEnum(imLabel.getStatus()), imLabel.getCreateTime(), imLabel.getUpdateTime()}).toArray(Object[][]::new);
        DbUtil.transaction((queryRunner, connection) -> {
            ColumnListHandler<Long> resultSetHandler = new ColumnListHandler();
            String sql = String.format("insert into im_label(serverId, currentUserId, name, status, createTime, updateTime) values(?, ?, ?, ?, ?, ?)");
            List<Long> ids = queryRunner.insertBatch(connection, sql, resultSetHandler, params);
            int idx = 0;
            for(Long id : ids) {
                imLabels.get(idx++).setId(id);
            }
            return ids.size();
        });
    }

    public void update(ImLabel imLabel) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            ResultSetHandler<Long> resultSetHandler = new ScalarHandler();
            String sql = String.format("update im_label set serverId = ?,  status =?, updateTime = ? where id = ? ");
            int n = queryRunner.update(connection, sql, resultSetHandler, imLabel.getServerId(), valueEnum(imLabel.getStatus()), imLabel.getUpdateTime(),
                    imLabel.getId());
            if (n != 1) {
                throw new RuntimeException("更新数据失败");
            }
            return imLabel;
        });
    }

    public void batchUpdate(List<ImLabel> imLabels) throws SQLException {
        if (imLabels.size() < 1) return;
        Object[][] params = imLabels.stream().map(imLabel-> new Object[]{imLabel.getServerId(), imLabel.getName(), valueEnum(imLabel.getStatus()), imLabel.getUpdateTime(),
                        imLabel.getId()}).toArray(Object[][]::new);

        DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("update im_label set serverId = ?, name =?,  status =?, updateTime = ? where id = ? ");
            int[] ns = queryRunner.batch(connection, sql, params);
            if (ns.length != imLabels.size()) {
                throw new RuntimeException("更新数据失败");
            }
            return ns.length;
        });
    }

    public ImLabel getByName(String userId, String name) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select %s from im_label where currentUserId=? and name = ? ", COLLECT_COLUMNS);
            ImLabelExt imLabelExt = queryRunner.query(connection, sql, new BeanHandler<ImLabelExt>(ImLabelExt.class), userId, name);
            return imLabelExt;
        });
    }

    public ImLabel getByServerId(String userId, String serverId) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select %s from im_label where currentUserId=? and serverId = ?", COLLECT_COLUMNS);
            ImLabelExt imLabelExt = queryRunner.query(connection, sql, new BeanHandler<ImLabelExt>(ImLabelExt.class), userId, serverId);
            return imLabelExt;
        });
    }


}
